package de.schillermann.register;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.entity.Player;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.Command;
import org.bukkit.configuration.file.FileConfiguration;

/**
 *
 * @author mario
 */
public class Main extends JavaPlugin {

    private String pluginName = "Register";
    private FileConfiguration config = null;
        
    @Override
    public void onEnable() {

        config = getConfig();
	config.options().copyDefaults(true);
        
        if(new File("plugins/" + pluginName + "/config.yml").exists())
        {			
            this.getLogger().info("[" + pluginName + "] config.yml loaded.");	
	}
        else
        {
            saveDefaultConfig();
            this.getLogger().info("[" + pluginName + "] config.yml created and loaded.");
	}
    }
    
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        
        Player player = null;

        if (!(sender instanceof Player)) {
            sender.sendMessage("This command can only be run by a player.");
            return true;
        }
        
        player = (Player) sender;
        
        if(args.length != 2) {
            return false;
        }

        if(!isValidEmail(args[0]))
        {
            player.sendMessage(
                ChatColor.translateAlternateColorCodes(
                    '&',
                    config.getString("not_valid_email")
                )
            );

            return true;
        }
        
        if(!isValidPassword(args[1]))
        {
            player.sendMessage(
                ChatColor.translateAlternateColorCodes(
                    '&',
                    config.getString("not_valid_password")
                )
            );

            return true;
        }

        try
        {
            String apiUrl = getApiUrl();
            
            String urlParameters =
                "username=" + URLEncoder.encode(player.getName(), "UTF-8") +
                "&password=" + URLEncoder.encode(args[1], "UTF-8") +
                "&email=" + URLEncoder.encode(args[0], "UTF-8") +
                "&ip=" + URLEncoder.encode(player.getAddress().getHostString(), "UTF-8");

            player.sendMessage(
                ChatColor.translateAlternateColorCodes(
                    '&',
                    config.getString("in_progress")
                )
            );
            
            String request = excutePost(apiUrl, urlParameters);
            
            if(config.getBoolean("debug") == true)
            {
                player.sendMessage(ChatColor.GOLD + "***** " + pluginName + " Debug Output *****");
                player.sendMessage(ChatColor.GOLD + "Http Request: \"" + request + "\"");
                player.sendMessage(ChatColor.GOLD + "From Url: \"" + apiUrl + "\"");
            }
            
            player.sendMessage(
                ChatColor.translateAlternateColorCodes(
                    '&',
                    config.getString(request)
                )
            );
        }
        catch(Exception e)
        {
            this.getLogger().severe("[" + pluginName + "] Can't connecting to Forum. Exception Message: " + e.getMessage());
            return true;
        }
        
        return true;
    }
    
    /**
     * Excute Post
     * 
     * @param targetURL
     * @param urlParameters
     * @return return first output line from http request
     */
    private String excutePost(String targetURL, String urlParameters)
    {
        URL url;
        HttpURLConnection connection = null;  
        try {
            //Create connection
            url = new URL(targetURL);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", 
                 "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length", "" + 
                     Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "de");  

            connection.setUseCaches (false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream (
                        connection.getOutputStream ());
            wr.writeBytes (urlParameters);
            wr.flush ();
            wr.close ();

            //Get Response	
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            
            String line =  rd.readLine();
            rd.close();
            return line;

        } catch (Exception e) {

            this.getLogger().severe("[" + pluginName + "] Can't send a Http Request. Exception Message: " + e.getMessage());
            return null;

        } finally {

            if(connection != null) {
                connection.disconnect(); 
            }
        }
    }
    
    private String getApiUrl()
    {
        if(config.getString("api_url") == null)
        {
            this.getLogger().severe("[" + pluginName + "] api_url is empty in the config file");
        }
        return config.getString("api_url");
    }
    
    private boolean isValidEmail(String email)
    {
        if(email.length() > 100)
        {
            return false;
        }
        return email.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
    }
    
    private boolean isValidPassword(String password)
    {
        return password.length() > 5 || password.length() < 101;
    }
}
